package com.woniu.backstage.exception;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br> 
 * 〈全局异常处理〉
 */
@Component
public class ExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        if ("XMLHttpRequest".equals(httpServletRequest.getHeader("X-Requested-With"))){
            FastJsonJsonView fastJsonJsonView = new FastJsonJsonView();
            Map<String, String> map = new HashMap<>();
            if (e instanceof LoginException){
                String message = e.getMessage();
                map.put("code","404");
                map.put("message",message);
                fastJsonJsonView.setAttributesMap(map);
                modelAndView.setView(fastJsonJsonView);
                return modelAndView;
            }
            map.put("code","404");
            String message = e.getMessage();
            map.put("message",message);
            fastJsonJsonView.setAttributesMap(map);
            modelAndView.setView(fastJsonJsonView);
            return modelAndView;
        }
        modelAndView.setViewName("static/index.html");
        return modelAndView;
    }
}